$(function() {
  class UpdateUserInfo {
    constructor() {
      this.init();
    }
    init() {
      //获取用户id 和 token
      this.id = cookie('id') ? cookie('id') : null;
      this.token = cookie('token') ? cookie('token') : null;
      this.isLogin();
      this.initDom();
      this.putInfo();
      this.bindEvent();
    }
    initDom() {
      //获取用户昵称
      this.nickname = $('#usernickname');
      //获取性别
      this.gender = null;
      //获取年龄
      this.userage = $('#userage');
      //保存按钮
      this.save_btn = $('#update_btn');
    }
    bindEvent() {
      this.save_btn.on('click', async() => {
        this.gender = $('input[name=gender]:checked');
        let res = await this.sendUpdateUserInfo();
        if(res.data.code === 1) {
          localStorage.setItem('usermsg', JSON.stringify({
            gender: $('input[name=gender]:checked').val(),
            nickname: this.nickname.val(),
            age: this.userage.val()
          }));
          new Toast({
            message: res.data.message,
            color: '#67C23A',
            callback() {
              location.reload();
            }
          });
        }else {
          new Toast({
            message: '表单信息有误,请重新检查输入',
            color: '#F56C6C'
          });
        }
      })
    }
    //发送修改密码请求
    sendUpdateUserInfo() {
      return axios({
        url: 'http://127.0.0.1:8888/users/update',
        method: 'POST',
        data: formData({
          id: this.id,
          age: this.userage.val(),
          gender: this.gender.val(),
          nickname: this.nickname.val()
        }),
        headers: {
          Authorization: this.token
        }
      });
    }
    //判断用户是否登陆
    isLogin() {
      if(!(this.id && this.token)) {
        new Toast({
          message: '用户未登陆或认证已过期，请您登录后再进行操作',
          color: '#E6A23C',
          callback() {
            location.href = './login.html';
          }
        });
      }
    }
    //优先从local中读取用户信息填入
    putInfo() {
      let userInfo = JSON.parse(localStorage.getItem('usermsg'));
      if(userInfo.nickname) {
        this.nickname.val(userInfo.nickname);
      }
      if(userInfo.age) {
        this.userage.val(userInfo.age);
      }
      if(userInfo.gender) {
        $('input[name=gender]').each((i, ele) => {
          if($(ele).val() === userInfo.gender) {
            $(ele).prop('checked', true);
          }
        });
      }
    }
  }
  new UpdateUserInfo();
}) 